import axios from 'axios';
import { message as $message } from 'ant-design-vue';
// import notification from 'ant-design-vue/es/notification'
// import { uniqueSlash } from './urlUtils';
import type { AxiosRequestConfig } from 'axios';
import { ACCESS_TOKEN } from '@/enums/cacheEnum';
import { Storage } from '@/utils/Storage';
// import { useUserStore } from '@/store/modules/user';
// import {ExclamationCircleOutlined} from '@ant-design/icons'
import { Modal } from 'ant-design-vue';

export interface RequestOptions {
  /** 是否直接获取data，而忽略message等 */
  isGetDataDirectly?: boolean;
  /** 请求成功是提示信息 */
  successMsg?: string;
  /** 请求失败是提示信息 */
  errorMsg?: string;
}

const UNKNOWN_ERROR = '未知错误，请重试';
// 是否生产环境
// const IS_PROD = ['production', 'prod'].includes(process.env.NODE_ENV);
/** 真实请求的路径前缀 */
// const baseApiUrl = process.env.VUE_APP_BASE_API;

const service = axios.create({
  // todo 从配置文件取
  baseURL: 'http://localhost:8889/officemanage-svr',
  timeout: 6000,
});

service.interceptors.request.use(
  (config) => {
    const token = Storage.Get(ACCESS_TOKEN);
    if (token) {
      // 请求头token信息，请根据实际情况进行修改
      config.headers['Authorization'] = token;
    }
    return config;
  },
  (error) => {
    Promise.reject(error);
  },
);

service.interceptors.response.use(
  (response) => {
    const headers = response.headers
    // 如果后端响应了token则更新token
    if (headers.authorization) {
      Storage.Set(ACCESS_TOKEN, headers.authorization);
    }

    const res = response.data;

    // if the custom code is not 200, it is judged as an error.
    if (res.code !== 0) {
      // debugger
      // todo 全局接口异常处理
      $message.error(res.msg || UNKNOWN_ERROR);
      // Illegal token
      if (res.msg === '没有登录') {
        // to re-login
        Modal.confirm({
          title: '警告',
          content: res.msg || '账号异常，您可以取消停留在该页上，或重新登录',
          okText: '重新登录',
          cancelText: '取消',
          onOk: () => {
            localStorage.clear();
            window.location.reload();
          }
        });
      }

      // throw other
      const error = new Error(res.msg || UNKNOWN_ERROR) as Error & { code: any };
      error.code = res.code;
      return Promise.reject(error);
    } else {
      return res;
    }
  },
  (error) => {
    // 处理 422 或者 500 的错误异常提示
    const errMsg = error?.response?.data?.message ?? UNKNOWN_ERROR;
    $message.error({ content: errMsg, key: errMsg });
    error.message = errMsg;
    return Promise.reject(error);
  },
);

export type Response<T = any> = {
  code: number;
  msg: string;
  data: T;
};

export type BaseResponse<T = any> = Promise<Response<T>>;

/**
 *
 * @param method - request methods
 * @param url - request url
 * @param data - request data or params
 */
export const request = async <T = any>(
  config: AxiosRequestConfig,
  options: RequestOptions = {},
): Promise<T> => {
  try {
    const { successMsg, errorMsg, isGetDataDirectly = false } = options;
    const res = await service.request(config);
    successMsg && $message.success(successMsg);
    errorMsg && $message.error(errorMsg);
    return isGetDataDirectly ? res.data : res;
  } catch (error: any) {
    return Promise.reject(error);
  }
};
